
// https://zhuanlan.zhihu.com/p/99845040
import * as actionTypes from '../actionTypes'

// 测试用，这里是测试写法
// import { routeList } from '@/router/rootRouter'
import { getToken, setToken, removeToken, getRoutes, setRoutes, getUserInfo, setUserInfo } from '@/utils/auth'

const storage = {
  token: getToken() || null,
  userInfo: getUserInfo() || null,
  routes: getRoutes() || null
}

// M => model 模型
export function userTokenModel(state = storage, action) {
  switch (action.type) {
    case actionTypes.SAVE_TOKEN: {
      const token = action.data
      setToken(token)
      return { token }
    }
    case actionTypes.DEL_TOKEN: {
      removeToken()
      return { token: '' }
    }
    default:
      return state
  }
}

export function userInfoModel(state = storage, action) {
  switch (action.type) {
    case actionTypes.SAVE_USER_INFO: {
      const userInfo = action.data
      setUserInfo(userInfo)
      return { userInfo }
    }
    default:
      return state
  }
}

export function userRoutesModel(state = storage, action) {
  switch (action.type) {
    case "SAVE_ROUTES":
      const routes = action.data
      setRoutes(routes)
      return { routes }
    case "DEL_ROUTES":
      return { routes: '' }
    default:
      return state
  }
}
